package cn.gudian.cms.Admin

class AdminAuthController {
  def jcaptchaService
  def index = {
    AdminU user = AuthSession.getUser(session)
    if (user) {
      [user: user]
    } else {
      redirect(action: "login")
    }
  }
  /**
   * 登录页面
   */
  def login = {
    if (AuthSession.getUser(session))
      return redirect(action: 'admin')
    return [loginUser: params.loginUser]
  }

  /**
   * 登录验证功能
   * 登录判断：
   * 1.如果首字母是英文字母的话就证明是用户名或者邮箱，否则就是手机号码或者会员卡号，或者邮箱
   * 2，如果检测为邮箱 ,则用邮箱验证，否则用户验证，如果检测为手机号码 ,则用手机号码验证，否则卡会员
   * */
  def signin = {
    def loginUser = params.loginUser
    def password = params.password
    def authcode = params?.authcode
    if (!authcode || !jcaptchaService.validateResponse("loginImageCaptcha", session.id, authcode)) {
      flash.message = "&nbsp;&nbsp;验证码错误！"
      return redirect(action: 'login', params: params)
    }
    AdminUser user = AdminUser.findByUserNameAndPassword(loginUser, password)

    //如果user不为空，且可以使用  ,登录成功
    if (user) {
      AdminU u = new AdminU()
      u.setUserName(user.getUserName())
      u.setRealName(user.getRealName())
      u.setAdminRole(user.adminRole.getRoles())
      u.setArcTypeIDs(user.getArcTypeIDs())
      AuthSession.loginSession(session, u)
      user.loginNum++
      user.lastLoginIP = request.getRemoteHost()
      user.lastLoginTime = new Date()
      user.save()
      flash.message = "登陆成功"
      redirect(action: 'index')
      return
    } else {
      flash.message = "&nbsp;&nbsp;你的帐户名或密码错误。";
      def m = [loginUser: loginUser]
      redirect(action: 'login', params: m)
    }
  }

  /*有成功提示的注销方法*/
  def loginOut = {
    AuthSession.removeSession(session)
    session.invalidate();
    redirect(uri: "/")
  }
}
